package com.bl.pet.service.impl;

import com.bl.basic.exception.BusinessException;
import com.bl.basic.rocketmq.RocketMQProducer;
import com.bl.basic.service.IBaiduAiAuditService;
import com.bl.basic.util.CodeGenerateUtils;
import com.bl.basic.util.DistanceUtils;
import com.bl.basic.util.PageList;
import com.bl.basic.util.Point;
import com.bl.order.domain.OrderPetAcquisition;
import com.bl.order.mapper.OrderPetAcquisitionMapper;
import com.bl.org.domain.Employee;
import com.bl.org.domain.Shop;
import com.bl.org.mapper.EmployeeMapper;
import com.bl.org.mapper.ShopMapper;
import com.bl.pet.domain.Pet;
import com.bl.pet.domain.SearchMasterMsg;
import com.bl.pet.domain.SearchMasterMsgAuditLog;
import com.bl.pet.dto.AcceptDto;
import com.bl.pet.mapper.PetMapper;
import com.bl.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.bl.pet.mapper.SearchMasterMsgMapper;
import com.bl.pet.query.SearchMasterMsgQuery;
import com.bl.pet.service.ISearchMasterMsgService;
import com.bl.basic.service.impl.BaseServiceImpl;
import com.bl.user.domain.User;
import com.bl.user.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;



/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private  OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RocketMQProducer rocketMQProducer;


    /**
     *  保存寻主消息
     * @param smm
     * @param id 当前登录人
     */
    // @Transactional // 事务回滚
    @Override
    public void publish(SearchMasterMsg smm, Long id) {
        //1.先添加到数据库t_searchMasterMsg    state:0 待审核
        // user_id   shop_id
        // 通过logininfoid查询userid
        User user = userMapper.loadByLogininfoId(id);
        smm.setUserId(user.getId());
        smm.setState(1); // 1 待处理
        //  shop_id: 先计算最近店铺
        // 获取当前地址的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShopId(nearestShop.getId());
        searchMasterMsgMapper.save(smm);
        //2. 审核
        // 审核文字
        Boolean textboo = baiduAiAuditService.textAudit(smm.getTitle() +smm.getName()+ smm.getAddress() + smm.getCoatColor());
        // 审核图片
        Boolean imgboo = baiduAiAuditService.imageAudit(smm.getResources());
        if(textboo && imgboo ){
            // 通过
            // 1修改smm的状态和node
            smm.setState(1); // 1 带处理
            smm.setNote("审核成功！待处理！！！！");
            searchMasterMsgMapper.update(smm);
            // 2 添加 t_search_master_msg_audit_log
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(smm.getId());
            searchMasterMsgAuditLog.setState(1l);
            searchMasterMsgAuditLog.setNote("审核成功！待处理！！！！");
            searchMasterMsgAuditLog.setAuditTime(new Date());
            searchMasterMsgAuditLog.setAuditId(user.getId());
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
        }else {
            // 未通过
            smm.setState(0);
            //修改状态和日志
            smm.setNote("审核失败，内容非法，驳回");
            searchMasterMsgMapper.update(smm);
            //2.2.审核失败：修改寻主消息状态0 + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(smm.getId());
            //audit_id - 自动审核，没有添加审核人
            log.setState(0L);// 未通过
            log.setNote("审核失败，内容非法，驳回");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("审核失败，内容非法，驳回");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        // 通过logininfoid查询employee
        Employee emp = employeeMapper.loadByLogininfoId(id);

        // 待处理状态
        query.setState(query.getState());

        if(emp.getShopId()!=null){
            query.setShopId(emp.getShopId());
        }
        return super.queryPage(query);




    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
        // 查询到用户id
        User user = userMapper.loadByLogininfoId(id);

        query.setUserId(user.getId());  // <if userId！=null> and user_id=#{userId}<>

        return super.queryPage(query);

    }

    /**
     *  拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
       searchMasterMsgMapper.reject(id);
    }

    /**
     *  接单
     * @param dto
     * @param id
     */
    @Override
    public void accept(AcceptDto dto, Long id) {
        // 订单信息id
        Long msgId = dto.getMsgId();
        // 处理人
        Long empId = dto.getHandler();
        // 处理信息
        String note = dto.getNote();
        // 根据smmid查询订单，如果查的到，该订单正在处理中，
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadOrderByMsgId(msgId);
        if (orderPetAcquisition!= null){
            throw new BusinessException("订单正在处理中!!!!!!!");
        }

        // 生成一个pet 根据searchMasterMsg生成。
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        // 保存,返回自增id
        petMapper.save(pet);

        // 2. 生成一个收购订单：
        OrderPetAcquisition opa = initOrderPetAcquisition(dto,pet,searchMasterMsg);
        // 3. 保存订单
        orderPetAcquisitionMapper.save(opa);
        // 发送延迟消息
        rocketMQProducer.sendDelayMsg(opa.getOrderSn(),3);

    }



    /**
     *  生成一个收购订单对象
     * @param dto
     * @param pet
     * @param smm
     * @return
     */
    private OrderPetAcquisition initOrderPetAcquisition(AcceptDto dto, Pet pet, SearchMasterMsg smm) {

        // 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUserId()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(smm.getUserId());
        order.setShopId(smm.getShopId());
        order.setAddress(smm.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(dto.getMsgId());


        return order;
    }
    /**
     *  生成一个pet对象
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setResources(smm.getResources());
        pet.setTypeId(smm.getPetType());
        pet.setCreatetime(new Date());
        pet.setShopId(smm.getShopId());
        pet.setSearchMasterMsgId(smm.getId());
        pet.setNote(smm.getNote());
        return  pet;
    }
}
